package com.gofunbuy.util;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.lang.ref.SoftReference;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.HashMap;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.util.Log;

/**
 * 异步调用并显示网络图片
 * 
 * @author Administrator
 * 
 */
public class AsyncImageLoader {
	private static final String TAG = "AsyncImageLoader";

	private static HashMap<String, SoftReference<Drawable>> imageCache;

	public AsyncImageLoader() {
		imageCache = new HashMap<String, SoftReference<Drawable>>();
	}

	public Drawable loadDrawable(final String imageUrl,
			final ImageCallback imageCallback) {
		if (imageCache.containsKey(imageUrl)) {
			SoftReference<Drawable> softReference = imageCache.get(imageUrl);
			Drawable drawable = softReference.get();
			if (drawable != null) {
				return drawable;
			}
		}
		final Handler handler = new Handler() {
			public void handleMessage(Message message) {
				imageCallback.imageLoaded((Drawable) message.obj, imageUrl);
			}
		};
		new Thread() {
			@Override
			public void run() {
				Drawable drawable = loadImageFromUrl(imageUrl);
				imageCache.put(imageUrl, new SoftReference<Drawable>(drawable));
				// Log.v(TAG, "runrun" + imageUrl + drawable);
				Message message = handler.obtainMessage(0, drawable);
				handler.sendMessage(message);
			}
		}.start();
		return null;
	}

	public static Drawable loadImageFromUrl(String url) {
		URL m;
		InputStream i = null;
		try {
			m = new URL(url);
			i = (InputStream) m.getContent();
		} catch (MalformedURLException e1) {
			e1.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} catch (NullPointerException e2) {
			Log.e("000------000", "loader:" + url);
			e2.printStackTrace();
		}
		// Drawable d = Drawable.createFromStream(i, "src");
		BitmapFactory.Options options = new BitmapFactory.Options();
		options.inJustDecodeBounds = false;

		options.inSampleSize = 3; // width，hight设为原来的十分一

		Bitmap btp = BitmapFactory.decodeStream(i, null, options);
		Drawable d = new BitmapDrawable(btp);
		return d;
	}

	public interface ImageCallback {
		public void imageLoaded(Drawable imageDrawable, String imageUrl);
	}

	

	private String getFileNameByUri(String imageUrl) {
		return imageUrl.substring(imageUrl.lastIndexOf("/") + 1);
	}

	public Drawable loadBigDrawable(final String imageUrl,
			final ImageCallback imageCallback) {

		File img = new File(cacheFilePath, getFileNameByUri(imageUrl));

		if (imageCache.containsKey(imageUrl)) {
			SoftReference<Drawable> softReference = imageCache.get(imageUrl);
			Drawable drawable = softReference.get();
			if (drawable != null) {
				return drawable;
			}
		} else if (img.isFile()&&img.exists()) {
			try {
				ByteArrayOutputStream outStream = new ByteArrayOutputStream();
				byte[] bt = new byte[1024];

				InputStream in = new FileInputStream(img);
				int readLength = in.read(bt);
				while (readLength != -1) {
					outStream.write(bt, 0, readLength);
					readLength = in.read(bt);
				}
				byte[] data = outStream.toByteArray();
				Bitmap bitmap = BitmapFactory.decodeByteArray(data, 0,
						data.length);
				BitmapDrawable drawable = new BitmapDrawable(bitmap);
				imageCache.put(imageUrl, new SoftReference<Drawable>(drawable));
				if (drawable != null) {
					return drawable;
				}
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}			
		}
		final Handler handler = new Handler() {
			public void handleMessage(Message message) {
				imageCallback.imageLoaded((Drawable) message.obj, imageUrl);
			}
		};
		new Thread() {
			@Override
			public void run() {
				Drawable drawable = loadImageFromUrl2(imageUrl);
				imageCache.put(imageUrl, new SoftReference<Drawable>(drawable));
				Message message = handler.obtainMessage(0, drawable);
				handler.sendMessage(message);
			}
		}.start();
		return null;
	}
	public Drawable loadImageFromUrl2(String url) {
		URL m;
		InputStream i = null;
		try {
			m = new URL(url);
			i = (InputStream) m.getContent();
		} catch (MalformedURLException e1) {
			e1.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} catch (NullPointerException e2) {
			Log.e("000------000", "loader:" + url);
			e2.printStackTrace();
		}

		// Drawable d = Drawable.createFromStream(i, "src");
		BitmapFactory.Options options = new BitmapFactory.Options();
		options.inJustDecodeBounds = false;

		options.inSampleSize = 3; // width，hight设为原来的十分一

		Bitmap btp = BitmapFactory.decodeStream(i, null, options);
		Drawable d = new BitmapDrawable(btp);
		
		if(!cacheFilePath.exists()){
			cacheFilePath.mkdir();
		}
		File img = new File(cacheFilePath, getFileNameByUri(url));	
		if(!img.exists()){

			try {
				img.createNewFile();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		Log.e("pppp",img.getAbsolutePath());
		FileOutputStream fout;
		try {
			fout = new FileOutputStream(img.getAbsolutePath());
			ByteArrayOutputStream baos =new ByteArrayOutputStream();
			btp.compress(Bitmap.CompressFormat.PNG, 100, baos);
	        fout.write(baos.toByteArray()); 
	        fout.close(); 
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		return d;
	}
	public  File cacheFilePath = new File(Environment
			.getExternalStorageDirectory().getAbsoluteFile(), "gofun");
}
